package com.temple.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;

public class JwtUtils {
    public static String createJwt(String id, String subject, Long expireTime, String secret, String issuer) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        //设置现在时间
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        // We will sign our JWT with our ApiKey secret
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(secret);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

        // Let's set the JWT Claims
        JwtBuilder builder = Jwts.builder().setId(id).setIssuedAt(now).setSubject(subject).setIssuer(issuer)
                .signWith(signatureAlgorithm, signingKey);
        // if it has been specified, let's add the expiration
        long expMillis = nowMillis + expireTime;
        Date exp = new Date(expMillis);
        builder.setExpiration(exp);

        // Builds the JWT and serializes it to a compact, URL-safe string
        return builder.compact();
    }


    // Sample method to validate and read the JWT
    public static Claims parseJWT(String jwt, String sercret) {
        // This line will throw an exception if it is not a signed JWS (as
        // expected)
        Claims claims = Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary(sercret)).parseClaimsJws(jwt).getBody();
        return claims;
    }

}
